const { sign, student, course } = require('../models')

module.exports =  {
  /**
   * 新增一个签到
   * @return 成功时返回新增的签到，失败时返回失败信息
   */
  async addSign(ctx, next) {
    try {
        let result = await sign.create(ctx.request.body);
        return ctx.body = { status: 'ok', data: result };
    } catch (e) {
        return ctx.body = { status: 'fail', data: e.message };
    }
  },

  /**
   * 分页获取签到
   * @return 成功时返回分页的签到，失败时返回失败信息
   */
  async getSignByPage (ctx, next) {
    try {
      let pageNum = parseInt(ctx.query.pageNum), pageSize = parseInt(ctx.query.pageSize);
      let search = ctx.query.cid ? {course_id: ctx.query.cid} : null;
      let lists = await sign.find(search, null, { skip: (pageNum - 1) * pageSize, limit: pageSize }).sort({create_time: 'desc'});
      
      // 如果已经扫码则isScan为true
      let result = []
      for(list of JSON.parse(JSON.stringify(lists))) {
        list.course = await course.findById(list.course_id).populate('students');
        result.push(JSON.parse(JSON.stringify(list)))
      }
      result = result.map(sign => { // 签到表层
        sign.course.students = sign.course.students.map((stu, index) => { // 签到的课程的学生层
          // 如果签到的学生中拥有课程学生的id，说明已经扫码，设置这个学生isScan为1
          if(sign.students.indexOf(stu._id.toString()) > -1) {
            stu.isScan = 1
          }
          return stu
        })
        return sign      
      })
      
      let total = await sign.count();
      return ctx.body = { status: 'ok', data: {lists: result, total} };
    } catch (e) {
      return ctx.body = { status: 'fail', data: e.message };
    }
  },

  /**
   * 新增一个学生
   * @return 成功时返回更改后签到，失败时返回失败信息
   */
  async addStudent(ctx, next) {
    try {
      let result = await sign.findById(ctx.request.body.sign_id)
      if(result.students.indexOf(ctx.request.body.sid) > -1) {
        return ctx.body = { status: 'fail', data: '你已经签到过了' };
      }
      result.students.push(ctx.request.body.sid)
      result = await result.save({students: result})
      return ctx.body = { status: 'ok', data: result };
    } catch (e) {
      return ctx.body = { status: 'fail', data: e.message };
    }
  }

}